package com.xiaopangzi.stomp.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述:
 *
 * @author : sujinchen
 * @date : 2020/9/21
 */
public class MySTOMPWebSocketHandler implements WebSocketHandler {
    private Logger logger = LoggerFactory.getLogger(MySTOMPWebSocketHandler.class);
    private static ConcurrentHashMap<String, WebSocketSession> clients = new ConcurrentHashMap<String, WebSocketSession>();
    /**
     * 连接成功后
     * @param session
     * @throws Exception
     */
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String id = session.getId();
        clients.put(id, session);
        logger.info("{}已建立连接，clients数量:{}",id,clients.size());
    }

    /**
     * 获取请求消息
     * @param session
     * @param message
     * @throws Exception
     */
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        logger.info("{}获取消息，消息内容:{} >>>当前连接数量：{}", session.getId(), message.toString(), clients.size());
        sendAll(message);
    }

    /**
     * 消息处理异常
     * @param session
     * @param exception
     * @throws Exception
     */
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String id = session.getId();
        logger.info("{}消息处理异常，消息内容:{} >>>当前连接数量：{}",id,exception.getMessage(),clients.size());
    }

    /**
     * 关闭连接
     * @param session
     * @param closeStatus
     * @throws Exception
     */
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        String id = session.getId();
        logger.info("{}连接关闭，关闭信息:{} >>>当前连接数量：{}", id, closeStatus.toString(), clients.size());
        clients.remove(session.getId());
    }

    /**
     * 支持分块消息，默认即可
     * @return
     */
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 消息群发
     * @param message
     * @return
     * @throws IOException
     */
    public Object sendAll(Object message) throws IOException {
        TextMessage textMessage = null;
        if (message instanceof TextMessage) {
            textMessage = (TextMessage) message;
        } else {
            textMessage=new TextMessage(new StringBuffer(message.toString()));
        }
        for (Map.Entry<String, WebSocketSession> sessionEntry :
                clients.entrySet()) {
            WebSocketSession value = sessionEntry.getValue();
            String key = sessionEntry.getKey();
            value.sendMessage(textMessage);
            logger.info("用户{}为：【{}】接收消息：{}",key,value,message);

        }
        return true;
    }
}
